import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { Button, message } from 'antd';
import { WeaTableNew } from 'comsMobx';
import { WeaTab, WeaLocaleProvider, WeaButtonIcon } from 'ecCom';
import { AntdConfirm } from '../util';
import Edit from './Edit';

const { WeaTable } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
const CustomComp = function ({ children, func, record, ...rest }) {
  const onHandleClick = () => func(record.id);
  return (
    <a onClick={onHandleClick} {...rest}>
      {children}
    </a>
  );
};

@inject('settingStore', 'emailMenuStore', 'emailOpsStore')
@observer
class Folder extends Component {
  static defaultProps = {
    prefixCls: 'email-setting-folder',
  };

  constructor(props) {
    super(props);

    this.state = {
      clearVisible: false,
      editVisible: false,
      editTitle: '',
    };
  }

  componentDidMount() {
    const {
      settingStore: { folderStore, setStoreState },
    } = this.props;
    let rightMenuDatas = [
      {
        key: 'emailAutoClearLog',
        icon: <i className="icon-coms-common" />,
        content: getLabel(515459, '邮件清理日志'),
        onClick: this.showEmailClearLog,
      },
      {
        key: 'refresh',
        icon: <i className="icon-coms-Update-synchronization" />,
        content: getLabel(197, '搜索'),
        onClick: this.onSearch,
      },
    ];
    setStoreState({ rightMenuDatas });

    if (!window.weaEmailEngine) {
      // 异步加载别模块的静态资源
      eventRegister.loadModule(
        'b_email',
        () => {
          // 加载成功
          // store 中更新load加载状态
          folderStore.setLoaded(true);
        },
        () => {
          // console.log("加载失败");
          // 加载文件失败 的业务处理， 网络超时，没文件之类
        },
      );
    } else {
      folderStore.setLoaded(true);
    }

    this.onSearch();
  }

  componentWillUnmount() {
    const {
      settingStore: { folderStore },
    } = this.props;
    folderStore.clear();
  }

  onSearch = () => {
    const {
      settingStore: { folderStore },
    } = this.props;
    const { getMailFolder, getEmailSize } = folderStore;
    getEmailSize();
    getMailFolder();
  };

  onOperatesClick = (record, index, operate) => {
    const {
      settingStore: { folderStore, setStoreState },
      emailMenuStore,
      emailOpsStore,
    } = this.props;
    const { getMailFolder, operateUserMailFolder, getEmailSize } = folderStore;
    const clearFunc = () => {
      operateUserMailFolder({
        operation: 'clearStar',
        folderId: record.id,
      }).then((res) => {
        if (res.flag) {
          message.success(getLabel(384426, '清空成功'));
          getMailFolder('', true);
        } else {
          message.error(getLabel(384427, '清空失败'));
        }
      });
    };
    const delFunc = () => {
      operateUserMailFolder({ operation: 'del', folderId: record.id }).then(
        (res) => {
          if (res.flag) {
            message.success(getLabel(83472, '删除成功！'));
            getMailFolder('', true);
            emailMenuStore && emailMenuStore.getMenu();
          } else if (res.msg) {
            message.error(res.msg);
            getMailFolder('', true);
            emailMenuStore && emailMenuStore.getMenu();
          } else {
            message.error(getLabel(384401, '删除失败，请重试！'));
          }
        },
      );
    };
    const delteEmailFunc = () => {
      operateUserMailFolder({
        operation: 'delmail',
        folderId: record.id,
      }).then((res) => {
        if (res.flag) {
          message.success(getLabel(83472, '删除成功！'));
          getMailFolder('', true);
        } else {
          message.error(getLabel(384401, '删除失败，请重试！'));
        }
      });
    };
    const delForverFunc = () => {
      setStoreState({ loading: true });
      operateUserMailFolder({
        operation: 'deletePermanently',
        folderId: record.id,
      }).then((res) => {
        if (res.flag) {
          message.success(getLabel(83472, '删除成功！'));
          emailOpsStore.getEmailSize();
          getMailFolder('', true);
          getEmailSize();
        } else {
          message.error(getLabel(384401, '删除失败，请重试！'));
        }
        setStoreState({ loading: false });
      });
    };
    if (operate.index === '0') {
      // edit
      this.editFolder(record.id);
    } else if (operate.index === '1') {
      // clearStar
      AntdConfirm(
        { content: getLabel('510418', '确定要清除该分类所有邮件的星标吗？') },
        clearFunc,
      );
    } else if (operate.index === '2') {
      // delete
      AntdConfirm(
        {
          content: getLabel(
            '510422',
            '确定要删除文件夹吗？删除文件夹同时会删除邮件，删除的邮件可在垃圾箱里找到。',
          ),
        },
        delFunc,
      );
    } else if (operate.index === '3') {
      // delete email
      let content =
        record.id * 1 > 0
          ? getLabel(
              '510419',
              '确定要删除该文件夹的所有邮件吗？删除的邮件可在垃圾箱里找到。',
            )
          : getLabel(
              '510420',
              '确定要删除该分类的所有邮件吗？删除的邮件可在垃圾箱里找到。',
            );
      AntdConfirm({ content }, delteEmailFunc);
    } else if (operate.index === '4') {
      // delete email forever
      AntdConfirm(
        { content: getLabel('510421', '确定要永久删除该文件夹的所有邮件吗？') },
        delForverFunc,
      );
    }
  };

  getEditRef = (ref) => {
    this.editRef = ref;
  };

  editFolder = (id) => {
    if (!this.editRef) return;
    const {
      settingStore: { folderStore },
    } = this.props;
    const { setStoreState, getMailFolderBean } = folderStore;
    const func = () => {
      getMailFolderBean({ id });
      this.setState({
        editVisible: true,
        editTitle: getLabel(31224, '编辑文件夹'),
      });
      setStoreState({
        isEdit: true,
        editId: id,
      });
    };
    this.editRef.wrappedInstance.getData(func);
  };

  batchDel = () => {
    const {
      settingStore: { folderStore },
      emailMenuStore,
    } = this.props;
    const { getMailFolder, operateUserMailFolder, folderTable } = folderStore;
    const folderId = folderTable.selectedRowKeysAllPages.join();
    const delFunc = () => {
      operateUserMailFolder({ operation: 'del', folderId }).then((res) => {
        if (res.flag) {
          message.success(getLabel(83472, '删除成功！'));
          getMailFolder();
          emailMenuStore && emailMenuStore.getMenu();
        } else if (res.msg) {
          message.error(res.msg);
          getMailFolder('', true);
          emailMenuStore && emailMenuStore.getMenu();
        } else {
          message.error(getLabel(384401, '删除失败，请重试！'));
        }
      });
    };
    AntdConfirm(
      {
        content: getLabel(
          512808,
          '确定要删除选择的文件夹吗？删除文件夹同时会删除邮件，删除的邮件可在垃圾箱里找到',
        ),
      },
      delFunc,
    );
  };

  addFolder = () => {
    if (!this.editRef) return;
    this.editRef.wrappedInstance.getData();
    this.setState({
      editVisible: true,
      editTitle: getLabel(18475, '新建文件夹'),
    });
  };

  getColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        if (
          newColumn.dataIndex === 'folderName' &&
          record.randomFieldCk === 'true'
        ) {
          return (
            <CustomComp
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_CustomComp@fjs5u4@${record.id}`}
              title={text}
              record={record}
              func={this.editFolder}
            >
              {text}
            </CustomComp>
          );
        }
        return <div dangerouslySetInnerHTML={{ __html: valueSpan }} />;
      };
      return newColumn;
    });
    return newColumns;
  };

  showEmailClearLog = () => {
    const onHandleShowVisible = () => this.setState({ clearVisible: true });
    if (this.refs.autoclearref && this.refs.autoclearref.clearLog) {
      this.refs.autoclearref.clearLog.wrappedInstance.openDialog(
        '',
        onHandleShowVisible,
      );
    }
  };

  onEditCancel = () => this.setState({ editVisible: false });
  onClearCancel = () => this.setState({ clearVisible: false });
  onEditSubmit = (res) => {
    const {
      settingStore: { folderStore },
      emailMenuStore,
    } = this.props;
    const { getMailFolder } = folderStore;
    if (res.flag) {
      message.success(getLabel(83551, '保存成功！'));
      emailMenuStore && emailMenuStore.getMenu();
      getMailFolder('', true);
    } else {
      let errorMsg =
        res.message === 'repeat'
          ? getLabel('26603', '名称重复')
          : getLabel(21809, '保存失败，请重试！');
      message.error(errorMsg);
    }
  };

  render() {
    const {
      prefixCls,
      settingStore: { folderStore },
    } = this.props;
    const { folderTable, folderSize, loaded } = folderStore;
    const MailClearLogDialog =
      (window.weaEmailEngine &&
        window.weaEmailEngine.components &&
        window.weaEmailEngine.components.MailClearLogDialog) ||
      React.Fragment;
    const folderTitle = (
      <div className={`${prefixCls}-title`}>
        {getLabel(384429, '邮件共：')}
        {folderSize.totalSize}
        {getLabel(83083, '封')}&nbsp;&nbsp; {getLabel(384428, '未读邮件：')}
        {folderSize.unreadsize}
        {getLabel(83083, '封')}&nbsp;&nbsp; {getLabel(83085, '总空间')}{' '}
        {folderSize.totalspace}M：{getLabel(83084, '已用')}
        <span style={{ color: '#FF6600' }}>{folderSize.occupyspace}</span>
        M，{getLabel(25723, '剩余')}{' '}
        <span style={{ color: '#0066FF' }}>
          {folderSize.remainspace < 0 ? 0 : folderSize.remainspace}
        </span>
        M
      </div>
    );
    const tabButtons = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@2t42jj@clearlog`}
        type="primary"
        onClick={this.showEmailClearLog}
      >
        {getLabel(515459, '邮件清理日志')}
      </Button>,
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@5xwim1@addFolder`}
        buttonType="add"
        type="primary"
        onClick={this.addFolder}
      />,
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@ia5640@batchDel`}
        buttonType="del"
        type="primary"
        disabled={folderTable.selectedRowKeysAllPages.length === 0}
        onClick={this.batchDel}
      />,
    ];
    return (
      <div className={prefixCls}>
        <WeaTab
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTab@r5tqu0`}
          replaceLeft={folderTitle}
          buttons={tabButtons}
        />
        <WeaTable
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTable@vecl1c`}
          comsWeaTableStore={folderTable}
          getColumns={this.getColumns}
          onOperatesClick={this.onOperatesClick}
          hasOrder
          needScroll
        />
        {loaded &&
          window.weaEmailEngine &&
          window.weaEmailEngine.components &&
          window.weaEmailEngine.components.MailClearLogDialog && (
            <MailClearLogDialog
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_MailClearLogDialog@sp8dmk`}
              ref="autoclearref"
              visible={this.state.clearVisible}
              onCancel={this.onClearCancel}
            />
          )}
        <Edit
          ecId={`${(this && this.props && this.props.ecId) || ''}_Edit@z4dskj`}
          ref={this.getEditRef}
          title={this.state.editTitle}
          visible={this.state.editVisible}
          onCancel={this.onEditCancel}
          onSubmit={this.onEditSubmit}
        />
      </div>
    );
  }
}
export default Folder;
